package com.example.controller;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.enetity.Article;
import com.example.enetity.Result;
import com.example.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/article")
//支持跨域
@CrossOrigin
public class ArticleController {

    @Autowired
    private ArticleService service;

    @Autowired
    private StringRedisTemplate template;


    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        service.add(article);
        return Result.success("文章添加成功");
    }

//    分页查询
    @GetMapping
    public Result<IPage<Article>> getPage(Integer pageNum, Integer pageSize,
                                          @RequestParam(required = false) String categoryId , @RequestParam(required = false) String state) {

        String s = template.opsForValue().get("data");
        JSONObject jsonObject = JSONObject.parseObject(s);
        Map<String,Object> map = (Map<String,Object>)jsonObject;
        Integer id = (Integer) map.get("id");
        IPage<Article> pages = service.getPage(id, pageNum, pageSize, categoryId, state);
        System.out.println(pages.getRecords());
        return Result.success("主人，分页查询成功了哟",pages);
        //返回的数据在res.data.records里
    }

    @GetMapping("/getOne")
    public Result<Article> getArticlesById(Integer id) {
        Article article =  service.getOneById(id);
        return Result.success("信息查询成功", article);
    }

    @PutMapping
    public Result<String> updateArticle(@RequestBody  Article article) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Article::getId,article.getId());
        service.update(article, wrapper);
        return Result.success("已修改成功");
    }

    @DeleteMapping
    public Result<String> deleteArticle(Integer id) {
        service.removeById(id);
        return Result.success("已删除成功");
    }
}
